import requests
import time
from 代理.untils.user_agent import get_request_headers
from 代理.setting import TIMEOUT
import json
from 代理.untils.log import logger
from 代理.domain import Proxy

def check_proxy(proxy):
    '''
    用于检查指定代理ip 响应速度，匿名程度，支持协议
    :param proxy:
    :return:
    '''
    proxies={
        'http':'http://{}:{}'.format(proxy.ip,proxy.port),
        'https': 'http://{}:{}'.format(proxy.ip, proxy.port)
    }
    #测试代理ip
    http,http_nick_type,http_speed=check_http(proxies)
    https, https_nick_type, https_speed = check_http(proxies,False)

    if http and https:
        proxy.protocol=2
        proxy.nick_type=https_nick_type
        proxy.speed=https_speed
    elif http:
        proxy.protocol = 0
        proxy.nick_type = http_nick_type
        proxy.speed = http_speed
    elif https:
        proxy.protocol = 1
        proxy.nick_type = https_nick_type
        proxy.speed = https_speed
    else:
        proxy.protocol=-1
        proxy.nick_type = -1
        proxy.speed = -1
    return proxy
def check_http(proxies,is_http=True):
    #匿名程度：高匿：0，匿名：1，透明：2
    nick_type = -1
    speed =-1
    if is_http:
        test_url='http://httpbin.org/get'
    else:
        test_url = 'https://httpbin.org/get'
    try:
        #获取开始时间
        start=time.time()
        #发送请求
        res=requests.get(url=test_url,headers=get_request_headers(),proxies=proxies,timeout=TIMEOUT)

        if res.ok:
            #响应时间
            speed=round(time.time()-start,2)
            dic =json.loads(res.text)
            orgin=dic['origin']
            pro_coonection=dic['headers'].get('Proxy-Connection',None)
            #判断匿名程度
            if ',' in orgin:
                nick_type=2
            elif pro_coonection:
                nick_type=1
            else:
                nick_type=0
            return True,nick_type,speed
        return False,nick_type,speed
    except Exception as ex:
        #logger.exception(ex)
        return False, nick_type, speed

if __name__ == '__main__':
    proxy=Proxy(ip='222.246.21.157',port='4231')
    print(check_proxy(proxy))